package com.ly.mpayment.persist.common;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.ly.mpayment.core.util.XssShieldUtil;

/**
 * 过滤器
 * 
 * 
 *
 */
public class FilterHttpServletRequest extends HttpServletRequestWrapper {
//	private Map params;
//
//	public FilterHttpServletRequest(HttpServletRequest request, Map newParams) {
//		super(request);
//		this.params = newParams;
//	}

	@Override
	public String getParameter(String name) {
		// 返回值之前 先进行过滤
		return XssShieldUtil.stripXss(super.getParameter(XssShieldUtil.stripXss(name)));
	}

	@Override
	public String[] getParameterValues(String name) {
		// 返回值之前 先进行过滤
		String[] values = super.getParameterValues(XssShieldUtil.stripXss(name));
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				values[i] = XssShieldUtil.stripXss(values[i]);
			}
		}
		return values;
	}

	private final String body;

	public FilterHttpServletRequest(HttpServletRequest request) throws IOException {
		super(request);
		this.body = RequestReadUtils.read(request);
	}

	public String getBody() {
		return body;
	}

	@Override
	public ServletInputStream getInputStream() {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
		return new ServletInputStream() {

			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {

			}

			@Override
			public int read() {
				return bais.read();
			}
		};
	}

	@Override
	public BufferedReader getReader() {
		return new BufferedReader(new InputStreamReader(this.getInputStream()));
	}

}
